// open设置请求方式，responseType设置请求的文件类型，onload用来异步判断response是成功或者失败，
// 失败返回statusText状态信息
const ajax = (url) => {
  return new Promise((resolve, reject) => {
    // 发送ajax请求
    let xhr = new XMLHttpRequest()
    xhr.open('GET', url)
    // 请求返回的格式是json
    xhr.responseType = 'json'
    // 请求完成之后
    xhr.onload = () => {
      if (this.status === 200) {
        resolve(this.response)
      } else {
        // 返回错误信息
        reject(new Error(this.statusText))
      }
    }
    xhr.send()
  })
}
// jQuery是dataType
let myButton = document.getElementById('myButton')

function success(responseText) {
  console.log('成功')
  console.log(responseText) //responseTex
}
function fail(request) {
  console.log('失败')
  console.log(request)
}
myButton.addEventListener('click', (e) => {
  //使用ajax
  $.ajax({
    method: 'post',
    url: '/xxx',
    data: 'username=mtt&password=1',
    dataType: 'json', //预期服务器返回的数据类型,如果不写,就是响应里设置的
  }).then(success, fail) //$.ajax()返回一个promise
})
// 封装jQuery的ajax
window.jQuery.ajax = ({ method, path, body, headers }) => {
  //ES6语法
  //进行Promise封装
  return new Promise((resolve, reject) => {
    //这句话是套路,记住
    let request = new XMLHttpRequest()
    request.open(method, path) //配置

    for (const key in headers) {
      //遍历header,设置响应头
      let value = headers[key]
      request.setRequestHeader(key, value)
    }
    request.send(body) //发送,并配置响应体

    request.onreadystatechange = () => {
      if (request.readyState === 4) {
        if (request.status >= 200 && request.status <= 400) {
          resolve.call(undefined, request.responseText) //执行成功函数
        } else if (request.status >= 400) {
          reject.call(undefined, request) //执行失败函数
        }
      }
    }
  })
}
